Kotlin Koans 29 Fold

目次

Fold (Playground)

Description

Implement Shop.getSetOfProductsOrderedByEveryCustomer() using fold.

fold を読んで、Shop.getSetOfProductsOrderedByEveryCustomer()を実装してください。

listOf(1, 2, 3, 4).fold(1, {
    partProduct, element ->
    element * partProduct
}) == 24

Code

// Return the set of products that were ordered by every customer
fun Shop.getSetOfProductsOrderedByEveryCustomer(): Set<Product> {
    val allProducts = customers.flatMap { it.orders.flatMap { it.products }}.toSet()
    return customers.fold(allProducts, {
        orderedByAll, customer ->
        orderedByAll.intersect(customer.orders.flatMap { it.products }.toSet())
    })
}

Memo

← Posts